from flask import Blueprint, render_template, redirect, url_for, request
from flask_login import login_required, current_user
from app import db
from app.forms import TaskForm
from app.models import Task

todo_bp = Blueprint('todo', __name__)

@todo_bp.route('/')
@login_required
def index():
    form = TaskForm()
    tasks = current_user.tasks.all()
    return render_template('index.html', form=form, tasks=tasks)

@todo_bp.route('/add', methods=['POST'])
@login_required
def add_task():
    form = TaskForm()
    if form.validate_on_submit():
        task = Task(
            title=form.title.data,
            category=form.category.data,
            author=current_user
        )
        db.session.add(task)
        db.session.commit()
    return redirect(url_for('todo.index'))

@todo_bp.route('/delete/<int:task_id>')
@login_required
def delete_task(task_id):
    task = Task.query.get_or_404(task_id)
    db.session.delete(task)
    db.session.commit()
    return redirect(url_for('todo.index'))

@todo_bp.route('/toggle/<int:task_id>')
@login_required
def toggle_task(task_id):
    task = Task.query.get_or_404(task_id)
    task.done = not task.done
    db.session.commit()
    return redirect(url_for('todo.index'))